<template>
  <div class="createVolunteer">
    <div class="main">
      <div class="header">
        <img src="@/assets/images/robot.png" alt="back" class="robot-icon" />
        <div class="header-title">
          <div class="title-text">AI教育顾问</div>
          <div class="title-desc">
            {{ currentAItext }}
          </div>
        </div>
        <div class="progress">{{ progress }}%</div>
      </div>
      <div class="content-box" ref="contentBoxRef">
        <div class="content" v-show="showContent">
          <div
            class="content-item"
            v-for="(item, index) in visibleItems"
            :key="index"
          >
            {{ item.displayText }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  computed,
  watch,
  onUnmounted,
  nextTick,
} from 'vue';
import { useRouter } from 'vue-router';
import { useVolunteerStore } from '@/store/volunteer';
import { showLoadingToast } from 'vant';
import { smartVolunteerFilling } from '@/api/volunteer';

const router = useRouter();
const store = useVolunteerStore();

const titleTexts = {
  start: '正在生成志愿表...',
  end: '生成成功！',
};

const progress = ref(0);
const currentAItext = ref(titleTexts.start);
const showContent = ref(false);

// 添加内容框引用
const contentBoxRef = ref(null);

let timer = null;

const isSmartRecommend = computed(() => store.isSmartRecommend);
const volunteerInfo = computed(() => store.volunteerInfo);
const batchTypeList = computed(() => store.batchTypeList);
const defaultBatchType = computed(() => store.defaultBatchType);
const firstStepData = computed(() => store.firstStepData);
const secondStepData = computed(() => store.secondStepData);
const thirdStepData = computed(() => store.thirdStepData);

const currentSchoolLevel = ref({});

watch(
  [batchTypeList, defaultBatchType],
  ([newBatchTypeList, newDefaultBatchType]) => {
    if (newBatchTypeList && newDefaultBatchType) {
      currentSchoolLevel.value = newBatchTypeList.find(
        (item) => item.batchType == newDefaultBatchType
      );
    }
  },
  { immediate: true }
);

// 控制每个content-item的显示
const visibleItems = ref([]);
const currentItemIndex = ref(0);

// 监听内容变化，自动滚动到底部
watch(
  visibleItems,
  () => {
    scrollToBottom();
  },
  { deep: true }
);

// 内容列表
const contentItems = [
  {
    text: `嗯，用户是来自${volunteerInfo.value.regionName}的${
      volunteerInfo.value.subjectTypeDesc
    }组合考生，高考分数为${volunteerInfo.value.score}分，高于去年${
      volunteerInfo.value.regionName
    }${currentSchoolLevel.value?.batchTypeName?.replace('批', '')}分数线${
      volunteerInfo.value.score - currentSchoolLevel.value?.lineScore
    }分`,
  },
  {
    text: `用户报考地区是${
      firstStepData.value?.regionNameList?.join('、') || '不限'
    }， 院校类型为${
      firstStepData.value?.collegeType?.replace(/,/g, '、') || '不限'
    }，院校特色为${
      firstStepData.value?.dualClassName?.replace(/,/g, '、') || '不限'
    }`,
  },
  {
    text: `用户感兴趣的专业为${
      secondStepData?.value?.replace(/,/g, '、') || '不限'
    }`,
  },
  {
    text: `用户志愿表结构选择采用【${
      thirdStepData.value.name || '我要冲！'
    }】策略`,
  },
  {
    text: '正在思考中...',
    isThinking: true,
  },
  {
    text: '正在生成中...',
    isThinking: true,
  },
  {
    text: '生成成功！',
  },
];

const getTextLength = () => {
  return contentItems.reduce((acc, item) => acc + item.text.length, 0);
};

const textSpeed = 40; // 打字速度

// 计算总字符数
const totalCharacters = getTextLength();
// 计算思考状态的额外时间（毫秒）
const thinkingPauseTime = 1000; // 思考状态停顿1秒

// 跟踪已打字的字符数
const totalTypedCharacters = ref(0);

// 计算当前进度
const calculateProgress = () => {
  const currentTyped = totalTypedCharacters.value;
  const totalChars = totalCharacters;

  // 基础进度：前10%是初始加载
  const baseProgress = 10;

  // 打字进度：剩余90%按字符比例分配
  const typingProgress = (currentTyped / totalChars) * 90;

  return Math.min(100, Math.floor(baseProgress + typingProgress));
};

// 自动滚动到底部
let scrollTimeout = null;
const scrollToBottom = () => {
  if (contentBoxRef.value) {
    // 清除之前的定时器，避免频繁滚动
    if (scrollTimeout) {
      clearTimeout(scrollTimeout);
    }

    // 使用防抖机制，延迟执行滚动
    scrollTimeout = setTimeout(() => {
      nextTick(() => {
        try {
          // 使用平滑滚动效果
          contentBoxRef.value.scrollTo({
            top: contentBoxRef.value.scrollHeight,
            behavior: 'smooth',
          });
        } catch (error) {
          // 如果平滑滚动不支持，使用传统方式
          contentBoxRef.value.scrollTop = contentBoxRef.value.scrollHeight;
        }
      });
    }, 50); // 50ms 防抖延迟
  }
};

// 打字机效果
const typewriter = (text, index) => {
  if (index < text.length) {
    visibleItems.value[currentItemIndex.value].displayText = text.slice(
      0,
      index + 1
    );

    // 更新已打字字符数和进度
    totalTypedCharacters.value++;
    progress.value = calculateProgress();

    // 自动滚动到底部
    scrollToBottom();

    setTimeout(() => typewriter(text, index + 1), textSpeed);
  } else {
    // 当前项打字完成，准备显示下一项
    if (currentItemIndex.value < contentItems.length - 1) {
      // 如果是思考状态，添加额外停顿
      if (
        contentItems[currentItemIndex.value].text === '正在思考中...' ||
        contentItems[currentItemIndex.value].text === '正在生成中...'
      ) {
        setTimeout(() => {
          currentItemIndex.value++;
          const nextItem = contentItems[currentItemIndex.value];
          visibleItems.value.push({
            text: nextItem.text,
            displayText: '',
            visible: true,
          });

          // 新项目添加后滚动到底部
          scrollToBottom();

          typewriter(nextItem.text, 0);
        }, thinkingPauseTime); // 思考状态停顿
      } else {
        currentItemIndex.value++;
        const nextItem = contentItems[currentItemIndex.value];
        visibleItems.value.push({
          text: nextItem.text,
          displayText: '',
          visible: true,
        });

        // 新项目添加后滚动到底部
        scrollToBottom();

        typewriter(nextItem.text, 0);
      }
    } else {
      // 所有内容打字完成，设置进度为100%
      progress.value = 100;
      currentAItext.value = titleTexts.end;

      // 最终滚动到底部
      scrollToBottom();
      gotoVolunteerDetail();
    }
  }
};

const gotoVolunteerDetail = () => {
  const toast = showLoadingToast('跳转中...');
  setTimeout(() => {
    store.setIsSmartRecommend(false);
    store.setFirstStepData({});
    store.setSecondStepData('');
    store.setThirdStepData({});
    toast.close();
    router.replace({
      path: '/volunTeerDetail',
      query: {
        to: '/home',
      },
    });
  }, 1000);
};

// 更新进度的函数
const updateProgress = () => {
  if (progress.value < 10) {
    progress.value += 1;

    // 当进度达到10%时显示内容区域并开始打字
    if (progress.value >= 10 && !showContent.value) {
      showContent.value = true;
      // 初始化第一个item
      visibleItems.value.push({
        text: contentItems[0].text,
        displayText: '',
        visible: true,
      });

      // 显示内容后滚动到底部
      scrollToBottom();

      // 开始打字机效果
      typewriter(contentItems[0].text, 0);
      // 清除定时器，后续进度由打字效果控制
      clearInterval(timer);
    }
  }
};

const getRecommendStrategy = () => {
  // 获取thirdStepData中的冲稳保个数
  const rushNum = thirdStepData.value.rushNum;
  const steadyNum = thirdStepData.value.steadyNum;
  const guaranteedNum = thirdStepData.value.guaranteedNum;
  return `${rushNum}:${steadyNum}:${guaranteedNum}`;
};

const getSmartVolunteerFilling = async () => {
  try {
    const recommendStrategy = getRecommendStrategy();
    const params = {
      groupLevel: '1',
      subject: volunteerInfo.value.relSubject,
      searchAllowSubject: volunteerInfo.value.relSubject,
      subjectType: volunteerInfo.value.subjectType,
      recordYear: volunteerInfo.value.defaultYear,
      rankNum: +volunteerInfo.value.position,
      userScore: +volunteerInfo.value.score,
      userMinScore: +volunteerInfo.value.score - 70,
      userMaxScore: +volunteerInfo.value.score + 30,
      localRegionId: volunteerInfo.value.regionId,
      batchType: defaultBatchType.value,
      collegeSearch: {
        regionIdList: firstStepData.value.regionIdList,
        collegeType: firstStepData.value.collegeType,
        dualClassName: firstStepData.value.dualClassName,
        natureName: firstStepData.value.natureName,
        levelName: firstStepData.value.levelName,
      },
      professionSearch: {
        secondPositionTagNames: secondStepData.value,
      },
      isSmartRecommend: store.isSmartRecommend == false ? 2 : 1,
      recommendStrategy,
    };
    const res = await smartVolunteerFilling(params);
    if (res.code == 200) {
      console.log(res.data);
    }
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  getSmartVolunteerFilling();
  // 启动初始进度条动画（只到10%）
  timer = setInterval(updateProgress, 50); // 快速到达10%
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  // 清理滚动定时器
  if (scrollTimeout) {
    clearTimeout(scrollTimeout);
  }
});
</script>

<style scoped lang="scss">
.createVolunteer {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: url('@/assets/images/homeBg.png') no-repeat center center;
  background-size: 100% 100%;
  .top {
    position: absolute;
    padding: 28px 30px 28px 30px;
    .back {
      width: 40px;
      height: 40px;
    }
  }
  .main {
    padding-top: 58px;
    display: flex;
    flex-direction: column;
    width: 700px;
    box-sizing: border-box;
    margin: 0 auto;
    .header {
      display: flex;
      .robot-icon {
        width: 136px;
        height: 120px;
        margin-right: 18px;
      }
      .header-title {
        display: flex;
        flex-direction: column;
        .title-text {
          font-weight: bold;
          font-size: 32px;
          color: #000000;
          line-height: 67px;
          margin-bottom: 6px;
          white-space: nowrap;
        }
        .title-desc {
          font-weight: 400;
          font-size: 22px;
          color: #555555;
          line-height: 34px;
          white-space: nowrap;
        }
      }
      .progress {
        margin-left: auto;
        font-family: D-DIN-PRO;
        font-weight: bold;
        font-size: 52px;
        color: $primary-color;
        line-height: 67px;
      }
    }
    .content-box {
      margin-top: 40px;
      height: calc(100vh - 240px);
      overflow-y: auto;
      .content {
        padding: 20px;
        width: 700px;
        position: relative;
        box-sizing: border-box;
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-radius: 38px;
          padding: 2px;
          background: linear-gradient(
            180deg,
            rgba(255, 255, 255, 1),
            rgba(206, 231, 245, 1)
          );
          -webkit-mask: linear-gradient(#fff 0 0) content-box,
            linear-gradient(#fff 0 0);
          mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
          -webkit-mask-composite: xor;
          mask-composite: exclude;
          pointer-events: none;
          animation: borderBlink 2s infinite;
        }
        .content-item {
          font-weight: 400;
          font-size: 24px;
          color: $primary-color;
          line-height: 36px;
          padding: 12px 20px;
          background-color: #fff;
          border-radius: 12px;
          opacity: 0;
          transform: translateY(20px);
          animation: fadeInUp 0.5s ease forwards;
          &:not(:last-child) {
            margin-bottom: 12px;
          }
        }
      }
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes borderBlink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}
</style>
